//
//  TimeDevice.m
//  mendianjieke
//
//  Created by 响当当 on 9/2/19.
//  Copyright © 2019 dongzheng. All rights reserved.
//

#import "TimeDevice.h"

@interface TimeDevice()
@property (nonatomic,strong) dispatch_source_t timer;
@end

@implementation TimeDevice
/**
 *   初始化
 */
+ (TimeDevice *_Nonnull)manager
{
    static TimeDevice *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!manager) {
            manager = [[TimeDevice alloc]init];
        }
    });
    return manager;
}


- (void)createTimerWith:(NSString *)time Sucess:(void(^_Nonnull)(id _Nonnull acceptData))sucess
{
    __block int timeout = [time intValue]+1;
    
    //获取全局队列
    dispatch_queue_t global = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    //创建一个定时器，并将定时器的任务交给全局队列执行(并行，不会造成主线程阻塞)
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, global);
    
    self.timer = timer;
    
    //设置触发的间隔时间
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    
    
    //设置定时器的触发事件
    dispatch_source_set_event_handler(timer, ^{
        
        //1. 每调用一次 时间-1s
        timeout --;
        
        if (timeout <= 0) {
            
            
            sucess(@"1");
            //关闭定时器
            dispatch_source_cancel(timer);
            
        }
        
        
    });
    
    dispatch_resume(timer);
}



- (void)timeStop
{
    dispatch_source_cancel(self.timer);
}
@end
